// pages/songs-detail/index.js
import {
  APIMusic
} from "../../../service/api_music"
import {
  rankingStore,
  playerStore
} from "../../../store/index"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ranking: "",
    rankingSongObj: {},
    type: "",
    playlistSong: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const type = options.type
    this.setData({
      type
    })
    if (type === "ranking") {
      const ranking = options.ranking
      this.setData({
        ranking
      })
      rankingStore.onState(ranking, this.getRankingSong())

    } else if (type === "menu") {
      const id = options.id
      APIMusic.getSongDetail(id).then(res => {
        const playlistSong = res.playlist;
        this.setData({
          rankingSongObj: playlistSong
        })
      }).catch(err => {
        console.error(err);
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.ranking) {
      rankingStore.offState(this.data.ranking, this.getRankingSong)
    }
  },

  // 点击歌曲列表里面的一首歌
  handleSongClick(event){
    const index = event.currentTarget.dataset.index;
    playerStore.setState("playListSongs",this.data.rankingSongObj.tracks);
    playerStore.setState("playSongIndex",index)
  },

  // 设置 rankingSongObj 为取到的 res
  getRankingSong() {
    return (res) => {
      this.setData({
        rankingSongObj: res
      })
    }
  }
})